package v2.chapter9.jaas2;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

public class MyCallbackHandler implements CallbackHandler {

	@Override
	public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
		for (int i = 0; i < callbacks.length; i++) {
			if (callbacks[i] instanceof TextOutputCallback) {
				TextOutputCallback toc = (TextOutputCallback) callbacks[i];

				switch (toc.getMessageType()) {
				case TextOutputCallback.INFORMATION:
					System.out.println(toc.getMessage());
					break;
				case TextOutputCallback.ERROR:
					System.err.println("ERROR：" + toc.getMessage());
					break;
				case TextOutputCallback.WARNING:
					System.err.println("WARNING：" + toc.getMessage());
					break;
				default:
					throw new IOException("Unsupported message type: " + toc.getMessageType());
				}

			}else if(callbacks[i] instanceof NameCallback) {
				NameCallback nc=(NameCallback)callbacks[i];
				String name="user";
				nc.setName(name);
			}else if(callbacks[i] instanceof PasswordCallback) {
				PasswordCallback pc=(PasswordCallback)callbacks[i];
				String pwd="pwd";
				pc.setPassword(pwd.toCharArray());
			}else {
				throw new UnsupportedCallbackException (callbacks[i], "Unrecognized Callback");
			}
		}

	}

}
